package com.epalmpay.service.machinewasher;

import com.epalmpay.dto.machinewasher.MachineWasherInDTO;
import com.epalmpay.dto.machinewasher.MachineWasherOutDTO;
import com.epalmpay.dto.machinewasher.MachineWasherOutDTOList;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.MachineWasherLogMapper;
import com.epalmpay.mapper.MachineWasherMapper;
import com.epalmpay.mapper.MemberMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.TkRefund;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.payplat.result.RefundResult;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.status.Rescode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/3/15.
 */
@Service("machineWasherService")
public class MachineWasherServiceImpl implements IMachineWasherService{

    @Resource
    private MachineWasherMapper machineWasherMapper;

    @Resource
    private TradeOfflineMapper tradeOfflineMapper;

    @Resource
    private MachineWasherLogMapper machineWasherLogMapper;

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private IWalletService walletService;

    @Override
    public MachineWasherOutDTOList queryMachineWasherList(MachineWasherInDTO machineWasherInDTO, Page page) throws ApplicationException {
        MachineWasherOutDTOList machineWasherOutDTOList = new MachineWasherOutDTOList();

        Map<String,Object> param=new HashMap<String,Object>();
        param.put("groupId",machineWasherInDTO.getGroupId());
        param.put("agentName",machineWasherInDTO.getAgentName());
        param.put("shopName",machineWasherInDTO.getShopName());
        param.put("status",machineWasherInDTO.getStatus());
        param.put("joinStart",machineWasherInDTO.getJoinStart());
        param.put("joinEnd",machineWasherInDTO.getJoinEnd());
        param.put("shortid",machineWasherInDTO.getShortid());
        param.put("shopId",machineWasherInDTO.getShopId());
        param.put("boardid",machineWasherInDTO.getBoardid());

        int sumCount = machineWasherMapper.queryMachineWasherCount(param);
        page.setTotalResult(sumCount);
        if(sumCount<=0)
            return machineWasherOutDTOList;

        param.put("limit", page.getShowCount());
        param.put("start", page.getShowCount()*(page.getCurrentPage()-1));

        List<MachineWasherOutDTO> machineWasherListOutDTO = machineWasherMapper.queryMachineWasherList(param);
        machineWasherOutDTOList.setMachineWasherOutDTOList(machineWasherListOutDTO);
        return machineWasherOutDTOList;
    }

    @Override
    public MachineWasher selectMachineByBoardId(String boardid) {
        return machineWasherMapper.selectMachineByBoardId(boardid);
    }

    @Override
    public void refundOrder(TradeOffline to) throws Exception {
        TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderIdStatus(to.getOrderId(), (byte)1);
        TkRefund tkRefund = null;
        if(tradeOffline.getPayType() == 1) {//支付宝
            tkRefund = TkRefund.initialize("ALIPAY", tradeOffline.getMerchantNo(), tradeOffline.getOrderId(), tradeOffline.getRealAmount() + "",
                    tradeOffline.getRealAmount() + "", tradeOffline.getTerminalNo());
        } else if(tradeOffline.getPayType() == 3) {//微信
            tkRefund = TkRefund.initialize("WECHAT", tradeOffline.getMerchantNo(), tradeOffline.getOrderId(), tradeOffline.getRealAmount() + "",
                    tradeOffline.getRealAmount() + "", tradeOffline.getTerminalNo());
        } else if(tradeOffline.getPayType() == 13) {//钱包支付，直接退款并修改状态
            Member member = memberMapper.queryGroup(tradeOffline.getPayerId());
            if(member!=null){
                //这里暂时把退款金额 全部退款至不可提现金额
                walletService.updateUserLockedAmount(member.getVirtualCard(), member.getPayGroupCode(), member.getUserId(), tradeOffline.getRealAmount()+"", "0", 0,tradeOffline.getOrderId());
                tradeOffline.setOrderId(tradeOffline.getOrderId());
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.ISRefund.getType());
                tradeOfflineMapper.updateByOrderIdSelective(tradeOffline);
            }
        }

        if(tkRefund != null) {
            RefundResult payResult = IPayAPI.finishTkRefund(tkRefund);

            //修改订单状态
            TradeOffline newto = new TradeOffline();
            newto.setOrderId(tradeOffline.getOrderId());
            newto.setTransactionStatus((byte) BizEnum.TransactionStatus.ISRefund.getType());
            tradeOfflineMapper.updateByOrderIdSelective(newto);
            if (!payResult.getResult_code().equals("000000")) {
                throw new ApplicationException(Rescode.FAIL, "退款调用失败" + payResult.getResult_msg());
            }
            
            
            
        }
    }

    @Override
    public int updateMachineWasherByShortId(Map<String, Object> param) {
       return machineWasherMapper.updateMachineWasherByShortId(param);
    }


    @Override
    public void updateAddress(MachineWasherInDTO machineWasherInDTO) throws ApplicationException {
        MachineWasher machineWasher = new MachineWasher();
        machineWasher.setId(machineWasherInDTO.getId());
        machineWasher.setAddress(machineWasherInDTO.getAddress());
        machineWasherMapper.updateByPrimaryKeySelective(machineWasher);
    }

    @Override
    public MachineWasherOutDTOList queryWashDetail(MachineWasherInDTO machineWasherInDTO, Page page) throws ApplicationException {
        MachineWasherOutDTOList machineWasherOutDTOList = new MachineWasherOutDTOList();
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("boardid",machineWasherInDTO.getBoardid());
        param.put("orderNo",machineWasherInDTO.getOrderNo());

        int sumCount = machineWasherLogMapper.queryMachineWasherLogCount(param);
        page.setTotalResult(sumCount);
        if(sumCount<=0)
            return machineWasherOutDTOList;

        param.put("limit", page.getShowCount());
        param.put("start", page.getShowCount()*(page.getCurrentPage()-1));

        List<MachineWasherOutDTO> machineWasherListOutDTO = machineWasherLogMapper.queryMachineWasherLogList(param);
        machineWasherOutDTOList.setMachineWasherOutDTOList(machineWasherListOutDTO);
        return machineWasherOutDTOList;
    }

    @Override
    public void editWash(MachineWasherInDTO machineWasherInDTO) throws ApplicationException {
        MachineWasher machineWasher = new MachineWasher();
        machineWasher.setId(machineWasherInDTO.getId());
        machineWasher.setBoardid(machineWasherInDTO.getNewBoardid());
        machineWasherMapper.updateByPrimaryKeySelective(machineWasher);

        machineWasherLogMapper.updaetWashLogByBoardid(machineWasherInDTO.getBoardid(),machineWasherInDTO.getNewBoardid());
    }

    @Override
    public MachineWasherLog queryWashAddress(String orderId) {
        return machineWasherLogMapper.queryWashAddress(orderId);
    }

    @Override
    public void batchEditWashBelong(MachineWasherInDTO machineWasherInDTO) {
        String[] ids = machineWasherInDTO.getWashIds().split(",");
        for (String id:ids){
            MachineWasher machineWasher = new MachineWasher();
            machineWasher.setId(Long.parseLong(id));
            machineWasher.setShopid(machineWasherInDTO.getShopId());
            machineWasher.setGmtModified(new Date());
            machineWasherMapper.updateByPrimaryKeySelective(machineWasher);
        }


    }

    @Override
    public MachineWasherLog queryWashInfoByOrderId(String orderId) throws ApplicationException {
        return machineWasherLogMapper.queryWashInfoByOrderId(orderId);
    }


}
